#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import os

from django.shortcuts import render

# Create your views here.
import jwt
from rest_framework.permissions import IsAuthenticated

import sys
import subprocess

from MyProjectServer.constants import PYTEST_PROJECT_PATH
from .models import TaskModel
from django.core.exceptions import ObjectDoesNotExist
from testcase.models import SpeakerProduct
from rest_framework.generics import ListAPIView
from .serializers import TaskModelSerializer, TaskModuleSerializer, TaskSerializer
from rest_framework.viewsets import ModelViewSet
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from speaker.models import SpeakerStatus
from speaker import speaker_monitor
import logging
logger = logging.getLogger('django')


class TaskAddAPIViewSet(ModelViewSet):
    """
    新增任务接口
    """
    # 权限检查
    permission_classes = [IsAuthenticated]

    queryset = TaskModel.objects.all()
    serializer_class = TaskModelSerializer

    def create(self, request, *args, **kwargs):
        logger.info('开始添加任务')
        logger.info('请求数据为：%s' % request.data)
        # 获取jwt中的用户信息
        request_jwt = request.headers.get("Authorization").replace("JWT ", "")
        request_jwt_decoded = jwt.decode(request_jwt, verify=False, algorithms=['HS512'])
        user_id = request_jwt_decoded["user_id"]
        logger.info('jwt用户id为%s' % user_id)
        task_data = {
            "title": request.data.get("title"),
            "task_type": request.data.get("task_type"),
            "creator": user_id,
            "is_smoke": request.data.get("is_smoke"),
            "desc": request.data.get("desc")
        }

        serializer = self.get_serializer(data=task_data)
        serializer.is_valid(raise_exception=True)
        task_id = self.perform_create(serializer).pk

        for item in request.data.get("testcase"):
            module_data = {
                "module": item
            }
            task_module_serializer = TaskModuleSerializer(data=module_data)
            task_module_serializer.is_valid(raise_exception=True)
            task_module_serializer.save(task_id=task_id)

        logger.info('添加任务成功！')
        return Response({"message": "任务添加成功！"}, status=status.HTTP_200_OK)

    def perform_create(self, serializer):
        return serializer.save()


class TaskListAPIView(ListAPIView):
    """
    任务列表查询接口
    """
    # 权限检查
    permission_classes = [IsAuthenticated]

    queryset = TaskModel.objects.all()
    serializer_class = TaskSerializer


class TaskStartAPIView(APIView):
    """
    任务开始接口
    """
    def post(self, request):
        task_id = request.data.get('task_id')
        port = request.data.get('port')
        speaker_version = request.data.get('sys_version')
        task = TaskModel.objects.get(id=task_id)
        is_smoke = task.is_smoke
        type_id = task.task_type_id

        if speaker_version != task.task_type.system_version:
            return Response({'message': '请选择正确的测试音箱！'}, status=status.HTTP_404_NOT_FOUND)

        # 判断该sn的音箱是否在线，如果出现异常，则返回无可用设备
        try:
            speaker = SpeakerStatus.objects.get(port=port)
        except ObjectDoesNotExist as e:
            return Response({'message': '未找到相关设备，请检查'}, status=status.HTTP_404_NOT_FOUND)

        if speaker.connect_status == 0:
            return Response({'message': '该设备处于未连接状态，请检查！'}, status=status.HTTP_404_NOT_FOUND)

        if speaker.run_status == 1:
            return Response({'message': '该设备正在运行中，请重新选择！'}, status=status.HTTP_404_NOT_FOUND)

        infos = None
        # 检测音箱详细信息
        if speaker.device_type == 0:
            infos = speaker_monitor.get_adb_infos(port=port)
        elif speaker.device_type == 1:
            infos = speaker_monitor.get_serial_infos(port=port)

        if infos is None:
            return Response({'message': '查询音箱详细信息失败，请检查！'}, status=status.HTTP_404_NOT_FOUND)

        version = infos.get('rom_version')
        detail = infos.get('detail')
        sn = infos.get('sn')
        com = speaker.port
        device_infos = {
            'task_id': task_id,
            'system_version': speaker_version,
            'sn': sn,
            'type_id': type_id,
            'is_smoke': is_smoke,
            'speakerVersion': version,
            'romVersion': version,
            'com': com
        }

        logger.info('device_infos: %s' % str(device_infos))

        # 拼接pytest命令行参数
        run_cmd = 'pytest -vs '
        testcase_path = PYTEST_PROJECT_PATH
        run_cmd += testcase_path
        for key, value in device_infos.items():
            param_str = f' --{key}={value}'
            run_cmd += param_str

        print(run_cmd)
        logger.info('run_cmd: %s' % run_cmd)
        # subprocess.Popen(run_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        subprocess.Popen(run_cmd)

        speaker.run_status = 1
        speaker.save()
        return Response({'message': '任务执行成功！', 'data': device_infos}, status=status.HTTP_200_OK)
